package com.example.stmp.AOP.Interceptor;

import cn.dev33.satoken.stp.StpUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.lang.reflect.Method;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            String methodName = method.getName();
            log.info("====拦截到了方法：{}，在该方法执行之前执行====", methodName);
        }

        String url = req.getRequestURI();

        // 放行登录和验证码请求
        if (url.contains("/login") || url.contains("/CaptchaGenerator")) {
            log.info("放行请求: {}", url);
            return true;
        }

        // 检查登录状态
        boolean isLogin = StpUtil.isLogin();
        log.info("令牌是否有效: {}", isLogin);

        if (isLogin) {
            return true;
        } else {
            log.warn("令牌无效，拒绝访问: {}", url);
            resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           @Nullable ModelAndView modelAndView) throws Exception {
        // 后处理逻辑（可选）
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                @Nullable Exception ex) throws Exception {
        // 清理逻辑（可选）
    }
}